#!/bin/bash
set -e
#check variables and print them
if [ $# -lt 1 ]; then
    echo "error.. need args"
    exit 1
fi
echo "commond is $0"
echo "args are:"
for arg in "$@"
do
    echo $arg
done
#set default variables
BACKUP_DIR=/home/backup
TODAY=$(date +%Y-%m-%d)
#change iptables
if  grep -q "$1" /etc/sysconfig/iptables
then 
	echo "$1 is already used!"
else 
	echo "Backup iptables to $BACKUP_DIR"
	cp -f /etc/sysconfig/iptables $BACKUP_DIR/iptables_$TODAY
	echo "Add $1 to iptables"
	# insert a rule before "-A INPUT -j REJECT --reject-with icmp-host-prohibited"
	sed -i "/-A INPUT -j REJECT --reject-with icmp-host-prohibited/i -A INPUT -m state --state NEW -m tcp -p tcp --dport $1 -j ACCEPT" /etc/sysconfig/iptables
	service iptables restart
fi